/**
 * Created by zdx  on 2016/8/26.
 *
 *
 */

define(["controller", "coordtransform"], function (c, coordtransform) {

    var server = c.server || "ws://g.air-cloud.cn:220/";
    var token = c.getToken() || "MSNBRE1JTiMxNDUyMDA0NzE5IzJmOWRmOGZmZTc1NTA3NzMxMGNmM2ZjNWIwM2FmMTVmZTdlMGExNGJjZGViYzcwZGQ1ODcwMTAxYjEzMTgzM2Q=";

    var planes = [];

    var currentTime = (new Date().getTime()/1000);
    function now_ts()
    {
        return currentTime;
    }

    function set_now_ts(ts) {
        currentTime = ts;
    }

/*    var now_ts = now_ts || function() {
        return parseInt((new Date()).getTime() / 1000);
    }*/

    var frame_num = 20;
    var cur_pos = [];

    function clear() {
        planes = [];
    }

    function consumer_point() {
        var now = now_ts();
        var points = [];
        for (var id in planes) {
            var data = planes[id];
            while (data.d[data.t + 1] && now - data.d[data.t].ts >= 90) {
                ++data.t;
            }
            if (data.d[data.t + 1]) {
                var diff_now = now - data.d[data.t].ts;
                if (diff_now > 60) {
                    if (data.speed <= 1.0) {
                        data.speed = Math.ceil(diff_now / 60);
                    }
                }
                else {
                    data.speed = 1.0;
                }
                var diff_ts = data.d[data.t + 1].ts - data.d[data.t].ts;
                if (diff_ts <= 0) {
                    data.t1 = 0;
                    next_pos = data.d[++data.t];
                }
                else {
                    var sum_frame = frame_num * diff_ts;
                    data.t1 += data.speed;
                    var next_pos;
                    if (data.t1 >= sum_frame) {
                        data.t1 = 0;
                        next_pos = data.d[++data.t];
                    }
                    else {
                        var k = data.t1 / sum_frame;
                        var diff_lat = data.d[data.t + 1].lat - data.d[data.t].lat;
                        var diff_lng = data.d[data.t + 1].lng - data.d[data.t].lng;
                        next_pos = {
                            "id": data.d[data.t].id,
                            "lat": data.d[data.t].lat + diff_lat * k,
                            "lng": data.d[data.t].lng + diff_lng * k,
                            "height": data.d[data.t].height,
                            "speed": data.d[data.t].speed,
                            "course": data.d[data.t].course
                        };
                    }
                }
                cur_pos[next_pos.id] = next_pos;
                points.push(next_pos);
            }
            else {
                points.push(data.d[data.t]);
            }
        }
        return points;
    }

    function get_all_track(id) {
        return planes[id] && planes[id].d;
    }

    function get_one_track(id)
    {
        var line = [];
        var data = planes[id];
        for (var i = 0; i <= data.t && data.d[i]; ++i)
        {
            line.push([data.d[i].lng, data.d[i].lat]);
        }
        if (cur_pos[id]) {
            line.push([cur_pos[id].lng, cur_pos[id].lat]);
        }
        return line;
    }

    function get_track()
    {
        var lines = [];
        for (var id in planes)
        {
            lines[id] = get_one_track(id);
        }
        return lines;
    }

    function add_point(data) {
        var id = data.id;
        if (!planes[id]) {
            planes[id] = {"t": 0, "t1": 0, "d": [], 'speed': 1.0};
        }
        if (!planes[id].d[0] || planes[id].d[planes[id].d.length - 1].ts < data.ts) {
            planes[id].d.push(data);
        }
        else {
            //TODO
        }
    }

    function connect() {
        var ws = new WebSocket(server + token);
        if (!ws) {
            alert("您的浏览器版本太低,不支持WebSocket,建议使用最新版本的Chrome Firefox或者IE");
            window.opener = null;
            window.open('', '_self');
            window.close();
        }
        ws.binaryType = "arraybuffer";
        ws.onopen = function () {
            console.log('websocket connected', server);
        };
        ws.onerror = function (error) {
            console.log("websocket", error);
        };
        ws.onmessage = function (a) {
            var LE = true;
            var d = new DataView(a.data);

            var len = d.getUint8(0);
            var id = String.fromCharCode.apply(null, new Uint8Array(a.data, 1, len));
            if ((d.byteLength - 1 - len) % 24 == 0) {
                var pos = {};
                for (var i = 1 + len; i < d.byteLength;) {
                    var ts = d.getUint32(i, LE);
                    i += 4;
                    var lat = (d.getInt32(i, LE) / 1e7);
                    i += 4;
                    var lng = (d.getInt32(i, LE) / 1e7);
                    i += 4;
                    var height = (d.getInt32(i, LE) / 1e3).toFixed(1);
                    i += 4;
                    var speed = (d.getUint32(i, LE) / 1e2).toFixed(1);
                    i += 4;
                    var course = (d.getUint32(i, LE) / 1e2).toFixed(1);
                    i += 4;
                    var lnglat = coordtransform.wgs84togcj02(lng * 1, lat * 1);
                    var tmp = {
                        "id": id,
                        "ts": ts,
                        "lat": lnglat[1],
                        "lng": lnglat[0],
                        "height": height,
                        "speed": speed,
                        "course": course
                    };
                    add_point(tmp);
                }

            }
            else {
                console.log("package length error ", d.byteLength, len);
            }
        };
        ws.onclose = function () {
            console.log('websocket disconnected, prepare reconnect');
            ws = null;
            setTimeout(connect, 100);
        };
    }

    connect();

    return{
        clear:          clear,
        set_now_ts:     set_now_ts,
        now_ts:         now_ts,
        frame_num:      frame_num,
        consumer_point: consumer_point,
        get_track:      get_track,
        get_one_track:  get_one_track,
        get_all_track:  get_all_track
    };
});
